define([
  "app"
],
  function(app) {
    var Music = app.module();
    Music.Collection = Backbone.Collection.extend({
      url: function () {
        return "https://api.douban.com/v2/music/search?tag=" + encodeURIComponent(this.tag) + "&callback=?";
      },

      cache: true,

      parse: function (obj) {
        if ( obj.musics.length ) {
          this.status = "valid";
          return obj.musics;
        }

        this.status = "invalid";
        return obj;
      },

      initialize: function (models, options) {
        if (options) {
          this.tag = options.tag;
        }
      }
    });

    Music.Views.Item = Backbone.View.extend({
      template: "music/item",

      tagName: 'li',

      serialize: function () {
        return { model: this.model };
      },

      // events: {
      //    "click": "changeMusic"
      // },

      // changeMusic: function (ev) {
      //   var model = this.model;
      //   var tag = app.router.musics.tag;
      //   var id = model.get("id");

      //   app.router.go("tag", tag, "id", id);
      // },

      initialize: function () {
        this.listenTo(this.model, "change", this.render);
      }
    });

    Music.Views.List = Backbone.View.extend({
      template: "music/list",

      serialize: function () {
        return { collection: this.options.musics };
      },

      beforeRender: function () {
        this.options.musics.each(function (music) {
          this.insertView("ul", new Music.Views.Item({
            model: music
          }));
        }, this);
      },

      afterRender: function () {
        this.$("input.invalid").focus();
      },

      initialize: function () {
        this.listenTo(this.options.musics, {
          "reset": this.render,

          "fetch": function () {
              this.$("ul").parent().html("搜索中请稍候...");
          }
        });
      },

      events: {
        "submit form": "updateMusic"
      },

      updateMusic: function (ev) {
        app.router.go( "tag", this.$('.tag').val() );
        return false;
      }
    });

    return Music;
});